import React from "react";
import {
    DeviceEventEmitter,
    Image,
    Linking,
    Platform,
    RefreshControl,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View,
} from "react-native";
import Swiper from "../../widgets/Swiper";
import colors from "../../utils/colors";
import screen from "../../utils/screen";
import Api from "../../utils/Api";
import RequestUtil from "../../utils/RequestUtil";
import Images from "../../images/Images";
import Marquee from "../../widgets/Marquee";
import ShadowBoxView from "../../widgets/ShadowBoxView";
import { AppInfo, getffly, numSub } from "../../utils/common";
import Constants from "../../utils/Constants";
import AsyncStorage from "@react-native-community/async-storage";
import Login from "./Login";
import { inject, observer } from "mobx-react";
import AppEvent from "../../utils/AppEvent";
import { AppModal } from "../../widgets/modal";
import { reset } from "../../utils/NavigationUtil";
import RTModule from "../../utils/RTModule";
import DeviceInfo from "react-native-device-info";
import store from "../../utils/SimpleStore";


@inject(['userStore'])
@observer
export default class Home extends React.Component{

    constructor(props){
        super(props)
        this.reportStat = this.reportStat.bind(this)
    }

    state={
        banners:[],
        data:null,
        currentNotify:null,
        isRefreshing:false,
        activityShareFission:{}
    }

    componentDidMount() {
        setTimeout(()=>{
            this.GetPopup()
            this.getData()
        },500)

        //获取本地用户信息
        this.props.userStore.getUser()

        this.loginListener = DeviceEventEmitter.addListener(AppEvent.login_expire, (data) => {

            this.props.userStore.logout()
            this.props.navigation.navigate("Home");
            this.loginDialog.show()
        });
        this.showLoginListener = DeviceEventEmitter.addListener(AppEvent.show_login, (data) => {

            this.loginDialog.show()
        });

        //获取app channel
        if(Platform.OS === 'android'){
            RTModule.getChannelId()
        }

        this.emitter = DeviceEventEmitter.addListener("update_home", (data) => {
            setTimeout(() => {
                this.getData();
            }, 300);
        });

        this.emitter2 = DeviceEventEmitter.addListener("notice", (data) => {
            console.log("notice::" + data);
            AppInfo.channel = "" + data
            store.get('report_stat').then(res=>{
                if(!res){
                    this.reportStat()
                    store.save('report_stat','report_stat')
                }
            })

        })
    }

    componentWillUnmount() {

        this.loginListener && this.loginListener.remove()
        this.emitter2 && this.emitter2.remove()
        this.emitter && this.emitter.remove()
        this.showLoginListener && this.showLoginListener.remove()
    }

    getData(){

        AppModal.showLoading();
        this.setState({isRefreshing:true})
        RequestUtil.get(Api.homeData).then(res=>{

            let data = res.data
            console.log('首页',data)
            if(data.user){
                this.props.userStore.setUser(null,data.user)
                AppInfo.helpdata = {...AppInfo.helpdata,userId:data.user.id}
            }
            if(data.areaCode){
                AppInfo.countryId  = data.areaCode
            }

            var banners = []
            if(data.banner){
                banners = data.banner;
            }
            if(data.activityShareFission){
                 AppInfo.activityShareFission = data.activityShareFission;
            }
            if(data.help){
                console.log('helo',data.help)
                AppInfo.helpdata = {...AppInfo.helpdata,...data.help}
            }
            this.setState({
                data:data,
                banners:banners,
                activityShareFission:data.activityShareFission,
                isRefreshing:false
            })
            AppModal.hideTip()
        },error=>{
            // AppModal.hideTip()
            this.setState({ isRefreshing:false })
            AppModal.showTip(error.msg)
            console.log('首页error',error)
        })

    }

    GetPopup(){
        RequestUtil.get(Api.getPopup,{}).then(data=>{

            var data = data.data;
            let dqdata = new Date().getTime();

            if (data && data.content) {

                var number1 = AsyncStorage.getItem("home_popup" + data.updatetime);
                if(global.token){
                    AsyncStorage.getItem('home_popup' + data.updatetime + global.token, function (err, number) {
                        if (number) {
                            let change = Number(numSub(dqdata, number));
                            console.log("change11", dqdata);
                            console.log("change22", number);
                            if (Number(change) > 0 && Math.floor(Number(change) / 1000 / 3600) >= 24) {
                                AsyncStorage.setItem("home_popup" + data.updatetime + global.token, "" + dqdata, (err) => { });
                                AppModal.alert(Constants.common.note, data.content,[{
                                    title:Constants.common.continue,
                                    onPress:()=>{
                                        AppModal.hideAlert()
                                    }
                                }]);
                            }
                            else {
                                console.log("change", change);
                            }
                        }
                        else {
                            AsyncStorage.setItem("home_popup" + data.updatetime + global.token, "" + dqdata, (err) => { });
                            AppModal.alert(Constants.common.note, data.content,[{
                                title:Constants.common.continue,
                                onPress:()=>{
                                    AppModal.hideAlert()
                                }
                            }]);
                        }
                    });
                }
                else {
                    AsyncStorage.getItem('home_popup' + data.updatetime, function (err, number) {
                        if (number) {
                            let change = Number(numSub(dqdata, number));
                            console.log("change11", dqdata);
                            console.log("change22", number);
                            if (Number(change) > 0 && Math.floor(Number(change) / 1000 / 3600) >= 24) {
                                AsyncStorage.setItem("home_popup" + data.updatetime, "" + dqdata, (err) => { });
                                self.dialogB.showDialog("",data.content,[i18n.t('common.continue')]);
                            }
                            else {
                                console.log("change", change);
                            }
                        }
                        else {
                            AsyncStorage.setItem("home_popup" + data.updatetime, "" + dqdata, (err) => { });
                            AppModal.alert(Constants.common.note, data.content,[{
                                title:Constants.common.continue,
                                onPress:()=>{
                                    AppModal.hideAlert()
                                }
                            }]);
                        }
                    });
                }

            }

        },error=>{
            console.log('checkupdate error',error)
        })
    }


    checkLogin = (callback)=>{
        if(this.props.userStore.isLogin){
            callback()
        }else{
            this.loginDialog.show()
        }
    }

    getOrderItem = (item)=> {
        AppModal.showLoading()
        RequestUtil.get(Api.taskList,{type:item.id}).then(res=>{
            console.log('task',res)
            let data = res.data

            AppModal.hideTip()

            if(data.task.length > 0){
                this.props.navigation.push("OrderGrabbing",{data:data});
            }else{
                AppModal.showTip("Currently unavailable")
            }

        },error=>{

            console.log('task error',error)
            console.log("error11" + JSON.stringify(error));
            AppModal.showError( error.msg);
        })

    }

    goActivityShareFission(){
        this.props.navigation.navigate("ActivityShareFission");
    }

    reportStat = ()=>{
        //上报channel
        let param =  {
            channnel:AppInfo.channel,
            event:'launch',
            id:DeviceInfo.getUniqueId(),
        }
        RequestUtil.post(Api.reportStat,param,true).then(res=>{
            console.log("report/stat::" + JSON.stringify(res));
            }, (error) => {
            console.log("report/stat_error11" + JSON.stringify(error));

        })
    }

    renderCard(item,index){
        // console.log('item',item)
        return (
            <View style={{marginTop: 10}}
                  key={index.toString()}
            >
                <ShadowBoxView
                    shadowOption={{
                        radius:screen.PIXEL_40,
                        color:'#000',
                        x:0,
                        y:0,
                        border:5
                    }}
                >
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.cardItem}
                        onPress={()=>{
                            this.checkLogin(()=>{
                                this.getOrderItem(item)
                            })
                        }}
                    >
                        <View style={styles.itemImgBg}>
                            <Image source={{uri:item.icon}}
                                   resizeMode={'contain'}
                                   style={styles.itemImage}/>
                        </View>
                        <View style={{flex:1,marginLeft:screen.PIXEL_30,justifyContent:'space-between'}}>
                            <View>
                                <Text style={{color:'#000',fontSize: 18}}>{item.name}</Text>
                                <Text style={{color:'#FF7B14',fontSize: 13}}>{Constants.home.member_lv } {item.minReq.level}</Text>
                            </View>

                            <View>
                                <Text style={{color:'#000',fontSize: 18}}>{Constants.home.from + Constants.appsymbol }
                                    <Text style={{fontFamily:getffly('bold')}}>{item.minReq.deposit}</Text>
                                </Text>
                                <TouchableOpacity
                                    style={{height:screen.scaleSize(66),backgroundColor:'#377C74',width:screen.PIXEL_270,
                                        justifyContent:'center',alignItems: 'center',marginTop: screen.PIXEL_10,
                                        borderRadius:screen.PIXEL_20,borderBottomRightRadius: screen.PIXEL_40
                                    }}
                                    onPress={()=>{
                                        this.checkLogin(()=>{
                                            this.getOrderItem(item)
                                        })
                                    }}
                                >
                                    <Text style={{color:'#fff',fontSize: 12}}>{Constants.order.grab_now}</Text>
                                </TouchableOpacity>
                            </View>

                        </View>
                    </TouchableOpacity>

                </ShadowBoxView>
            </View>
        )
    }

    renderHeader(){
        let title = 'Register/Login'
        const isLogin = this.props.userStore.isLogin
        if(isLogin){
            title = Constants.appname
        }
        const {currentNotify} = this.state
        let typeStr = Constants.team.referral_reward
        let rewardStr = ''
        if(currentNotify){
            typeStr = currentNotify.type
            rewardStr = `${currentNotify.name} +${currentNotify.amount}`
        }
        return (
            <View style={styles.header}>
                <View>
                    <Text style={isLogin ? styles.appTitle : styles.loginText }
                          onPress={()=>{
                              if(!isLogin){
                                  this.loginDialog.show()
                              }
                          }}
                    >{title}</Text>
                    <Text style={{color:'#000',fontSize:11}}>{typeStr}
                        <Text style={{color:'#DEB259'}}> {rewardStr}</Text>
                    </Text>
                </View>
                <TouchableWithoutFeedback
                    onPress={()=>{
                        this.checkLogin(()=>{
                            this.props.navigation.navigate('Order')
                        })
                    }}
                >
                    <Image source={Images.cart} style={styles.cart}/>
                </TouchableWithoutFeedback>
            </View>
        )
    }

    bannerClick = (item) => {
        console.log('click banner:' + JSON.stringify(item))
        if(item.targetType=='url'){
            this.props.navigation.push("Html", { title: Constants.appname, weburl: item.targetPath });
        }
        else if(item.targetType=='app'){
            this.props.navigation.push(item.targetPath);
        }
        else if(item.targetType=='game'){
            console.log('games:' + global.token)
            if(global.token){
                var gameurl = item.targetPath + global.token
                console.log('games url:' + gameurl )
                this.props.navigation.push("Html", { title: Constants.appname, weburl: gameurl });
            }
        }

    }

    renderTopSwiperItem = (item,index) => {
        return <TouchableOpacity
            key={index.toString()}
          activeOpacity={1.0}
            onPress={() => {
                        this.bannerClick(item)
                   }} >
            <Image
              source={{uri:item.imagePath}}
              style={{ width: screen.width, height: screen.PIXEL_260 }}
            />

       </TouchableOpacity>;
    }

    renderTopSwiper(){
        if(!this.state.banners.length) return  null

        return (
            <View style={{ width: '100%', height: screen.PIXEL_260, flexDirection: 'column',marginTop:screen.PIXEL_5 }}>
                <View style={{ width: screen.width, height: screen.PIXEL_260 }}>
                    <Swiper key={this.state.banners.length}
                          height={260}
                          loop={true}
                          index={0}
                          autoplay={true}
                          horizontal={true}>
                        {
                            this.state.banners.map((item,index)=>{
                                return this.renderTopSwiperItem(item,index)
                            })
                        }
                    </Swiper>
                </View>
            </View>
        )
    }

    renderActivityShareFission(){
        return (
             <View style={{width: screen.width, height: screen.PIXEL_270}}>
                <TouchableOpacity activeOpacity={0.7} onPress={() => {
                   this.goActivityShareFission();
               }}>
                {
                     <View style={{justifyContent: 'center', alignItems: 'center' }}>
                        <View style={{ overflow: 'hidden'}}>
                            <Image
                                source={{ uri: this.state.activityShareFission.banner }}
                                style={{ width: screen.width, height: screen.PIXEL_270 }}
                            />
                        </View>
                    </View>
                }
                </TouchableOpacity>
             </View>
        )
    }

    render(){

        const {data,isRefreshing} = this.state

        return (

            <View style={styles.container}>

                <View style={styles.content}>

                    {this.renderHeader()}

                    {this.renderTopSwiper()}

                   {
                       this.state.activityShareFission != null && this.props.userStore.isLogin && this.renderActivityShareFission()
                   }

                    {
                        data ? (
                            <ScrollView
                                style={{flex:1,marginBottom:10}}
                                contentContainerStyle={{
                                    paddingVertical:screen.PIXEL_20,
                                    paddingHorizontal:screen.PIXEL_40,
                                }}
                                refreshControl = {
                                    <RefreshControl
                                        refreshing={ isRefreshing }
                                        onRefresh = {() => {
                                            this.getData()
                                        }}
                                    />
                                }
                            >
                                <Marquee
                                    data={data.broadcast}
                                    onChange={item=>{
                                        // console.log('当前广播',item)
                                        this.setState({
                                            currentNotify:item
                                        })
                                    }}
                                />

                                {data.types.map((item,index)=>{
                                    return this.renderCard(item,index)
                                })}

                            </ScrollView>

                        ):null
                    }

                </View>

                {/*<DialogTip ref={ref=>this.tipDialog = ref} />*/}

                <Login ref={ref=>this.loginDialog = ref}
                       loginSuccess={()=>{
                           // this.getData()
                           reset(this.props.navigation,'Main')
                       }}
                       navigation={this.props.navigation}/>
            </View>
        )
    }
}




const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:colors.tabBgColor,

    },
    content:{
        flex:1,backgroundColor: '#fff',
        paddingTop:screen.statusBarHeight,
        borderBottomLeftRadius:screen.PIXEL_110,
        borderBottomRightRadius:screen.PIXEL_110
    },
    header:{
        flexDirection:'row',
        justifyContent:'space-between',
        paddingHorizontal:screen.PIXEL_60,
        marginVertical:screen.PIXEL_10
    },
    appTitle:{
        color:'#000',fontSize:19,fontWeight:'bold'
    },
    loginText:{
        color:'#A4A4A4',fontSize:19,fontWeight:'bold'
    },
    cart:{
        width:screen.scaleSize(73),
        height:screen.scaleSize(94)
    },
    cardItem:{
        width:'100%',height: screen.PIXEL_320,backgroundColor:'#fff',
        borderRadius:screen.PIXEL_40,padding:screen.PIXEL_30,
        flexDirection: 'row'
    },
    itemImgBg:{
        backgroundColor:'#E9F5F6',
        width:screen.scaleSize(227),
        height:screen.scaleSize(268),
        justifyContent: 'center',
        alignItems:'center',
        borderRadius: screen.PIXEL_30
    },
    itemImage:{
        width:screen.PIXEL_180,
        height:screen.PIXEL_200
    }
})
